<template>
	<view class="content">
		<u-form v-show="!$status" :model="form" ref="uForm" label-position="top" :border-bottom="false" :error-type="['toast']">
			<u-form-item :required="true" label="标题" placeholder="请输入标题" :border-bottom="false" prop="title">
				<u-input :border="true" maxlength="15" v-model="form.title" />
			</u-form-item>
			<u-form-item :required="true" label="类型" :border-bottom="false" prop="wall">
				<u-input type="select" @click="show_wall = true" placeholder="请选择类型" v-model="form.wall_title" :border="true" />
			</u-form-item>
			<u-form-item label="匿名" :border-bottom="false"><u-switch v-model="form.anonymous"></u-switch></u-form-item>
			<u-form-item label="封面" :border-bottom="false">
				<u-upload
					ref="uUpload"
					:action="action"
					name="file[]"
					max-count="1"
					:max-size="10 * 1024 * 1024"
					@on-success="upload"
					:before-upload="beforeUpload"
					@on-uploaded="onUploaded"
					@on-remove="onRemove"
				></u-upload>
			</u-form-item>
			<u-form-item :required="true" label="正文" :border-bottom="false" prop="content">
				<!-- <u-input type="textarea" maxlength="1024" :clearable="false" height="120" :auto-height="true" v-model="form.content" :border="true" /> -->
				<view class="editor">
					<editor
						:show-img-size="true"
						:show-img-toolbar="true"
						id="editor"
						:show-img-resize="true"
						class="ql-container"
						:placeholder="placeholder"
						@ready="onEditorReady"
						@input="input"
					></editor>
				</view>
				<view class="toolbar">
					<view class="icon_img" @touchend.stop="format">
						<i class="iconfont icon-charutupian" @touchend.stop="insertImage"></i>
						<i :class="'iconfont icon-format-header-1 ' + (formats.header === 1 ? 'ql-active' : '')" data-name="header" :data-value="1"></i>
						<i :class="'iconfont icon-format-header-2 ' + (formats.header === 2 ? 'ql-active' : '')" data-name="header" :data-value="2"></i>
						<i :class="'iconfont icon-format-header-3 ' + (formats.header === 3 ? 'ql-active' : '')" data-name="header" :data-value="3"></i>
						<i :class="'iconfont icon-format-header-4 ' + (formats.header === 4 ? 'ql-active' : '')" data-name="header" :data-value="4"></i>
						<i :class="'iconfont icon-format-header-5 ' + (formats.header === 5 ? 'ql-active' : '')" data-name="header" :data-value="5"></i>
						<i :class="'iconfont icon-format-header-6 ' + (formats.header === 6 ? 'ql-active' : '')" data-name="header" :data-value="6"></i>
						<i :class="'iconfont icon-zitijiacu ' + (formats.bold ? 'ql-active' : '')" data-name="bold"></i>
						<i :class="'iconfont icon-zitishanchuxian ' + (formats.strike ? 'ql-active' : '')" data-name="strike"></i>
						<i :class="'iconfont icon-zitixieti ' + (formats.italic ? 'ql-active' : '')" data-name="italic"></i>
						<i :class="'iconfont icon-zuoduiqi ' + (formats.align === 'left' ? 'ql-active' : '')" data-name="align" data-value="left"></i>
						<i :class="'iconfont icon-juzhongduiqi ' + (formats.align === 'center' ? 'ql-active' : '')" data-name="align" data-value="center"></i>
						<i :class="'iconfont icon-youduiqi ' + (formats.align === 'right' ? 'ql-active' : '')" data-name="align" data-value="right"></i>
						<i :class="'iconfont icon-zuoyouduiqi ' + (formats.align === 'justify' ? 'ql-active' : '')" data-name="align" data-value="justify"></i>
						<i :class="'iconfont icon-line-height ' + (formats.lineHeight ? 'ql-active' : '')" data-name="lineHeight" data-value="2"></i>
						<i :class="'iconfont icon-Character-Spacing ' + (formats.letterSpacing ? 'ql-active' : '')" data-name="letterSpacing" data-value="2em"></i>
						<i :class="'iconfont icon-722bianjiqi_duanqianju ' + (formats.marginTop ? 'ql-active' : '')" data-name="marginTop" data-value="20px"></i>
						<i :class="'iconfont icon-723bianjiqi_duanhouju ' + (formats.micon - previewarginBottom ? 'ql-active' : '')" data-name="marginBottom" data-value="20px"></i>
						<i class="iconfont icon-clearedformat" @tap="removeFormat"></i>
						<i :class="'iconfont icon-font ' + (formats.fontFamily ? 'ql-active' : '')" data-name="fontFamily" data-value="Pacifico"></i>
						<i :class="'iconfont icon-fontsize ' + (formats.fontSize === '24px' ? 'ql-active' : '')" data-name="fontSize" data-value="24px"></i>
						<i :class="'iconfont icon-fontbgcolor ' + (formats.backgroundColor === '#ff9f1a' ? 'ql-active' : '')" data-name="backgroundColor" data-value="#ff9f1a"></i>
						<i class="iconfont icon-date" @tap="insertDate"></i>
						<i class="iconfont icon-undo" @tap="undo"></i>
						<i class="iconfont icon-redo" @tap="redo"></i>
						<i :class="'iconfont icon-zitixiahuaxian ' + (formats.underline ? 'ql-active' : '')" data-name="underline"></i>
						<i class="iconfont icon--checklist" data-name="list" data-value="check"></i>
						<i :class="'iconfont icon-youxupailie ' + (formats.list === 'ordered' ? 'ql-active' : '')" data-name="list" data-value="ordered"></i>
						<i :class="'iconfont icon-wuxupailie ' + (formats.list === 'bullet' ? 'ql-active' : '')" data-name="list" data-value="bullet"></i>
						<i class="iconfont icon-outdent" data-name="indent" data-value="-1"></i>
						<i class="iconfont icon-indent" data-name="indent" data-value="+1"></i>
						<i class="iconfont icon-fengexian" @tap="insertDivider"></i>
						<i :class="'iconfont icon-zitixiabiao ' + (formats.script === 'sub' ? 'ql-active' : '')" data-name="script" data-value="sub"></i>
						<i :class="'iconfont icon-zitishangbiao ' + (formats.script === 'super' ? 'ql-active' : '')" data-name="script" data-value="super"></i>
						<i class="iconfont icon-shanchu" @tap="clear"></i>
						<i :class="'iconfont icon-direction-rtl ' + (formats.direction === 'rtl' ? 'ql-active' : '')" data-name="direction" data-value="rtl"></i>
						<!-- <i class="iconfont icon-baocun" @tap="store" id="1"></i> -->
					</view>
				</view>
			</u-form-item>
			<u-form-item><u-button @click="submit" :loading="loading" type="primary">发布</u-button></u-form-item>
		</u-form>
		<view v-show="$status">
			<u-collapse>
				<u-collapse-item :title="item.head" v-for="(item, index) in itemList" :key="index">{{ item.body }}</u-collapse-item>
			</u-collapse>
		</view>
		<u-toast ref="uToast" />
		<u-select v-model="show_wall" :list="wall_list" @confirm="confirm"></u-select>
	</view>
</template>

<script>
var _self;
import { upload, wall_list } from '@/api/index.js';
import { article_add } from '@/api/user.js';
export default {
	data() {
		return {
			itemList: [
				{
					head: '赏识在于角度的转换',
					body: '只要我们正确择取一个合适的参照物乃至稍降一格去看待他人，值得赏识的东西便会扑面而来',
					open: true
				},
				{
					head: '生活中不是缺少美，而是缺少发现美的眼睛',
					body: '学会欣赏，实际是一种积极生活的态度，是生活的调味品，会在欣赏中发现生活的美',
					open: false
				},
				{
					head: '周围一些不起眼的人、事、物，或许都隐藏着不同凡响的智慧',
					body: '但是据说雕刻大卫像所用的这块大理石，曾被多位雕刻家批评得一无是处，有些人认为这块大理石采凿得不好，有些人嫌它的纹路不够美',
					open: false
				}
			],
			action: upload,
			fileList: [],
			show_wall: false,
			wall_list: [], //墙类型
			disabled: false,
			loading: false,
			timer: null,
			value: '',
			formats: {},
			form: {
				title: '',
				content: '',
				wall_title: '',
				wall: '',
				anonymous: false
			},
			rules: {
				// 字段名称
				title: [
					{
						required: true,
						message: '请输入标题',
						trigger: ['blur']
					}
				],
				wall: [
					{
						required: true,
						// 自定义验证函数，见上说明
						validator: (rule, value, callback) => {
							if (value == '') {
								callback(new Error('请选择类型'));
							} else {
								callback();
							}
						},
						message: '请选择类型',
						// 触发器可以同时用blur和change
						trigger: ['change', 'blur']
					}
				]
			}
		};
	},
	onReady() {
		this.$refs.uForm.setRules(this.rules);
	},
	onLoad() {
		this.getList();
		_self = this;
	},
	methods: {
		getList() {
			wall_list().then(res => {
				if (res.code == 200) {
					this.wall_list = res.data.map(item => {
						return {
							label: item.title,
							value: item.wall
						};
					});
				} else {
					uni.showToast({
						title: '获取类型失败!'
					});
				}
			});
		},
		confirm(arr) {
			console.log(arr);
			this.form.wall = arr[0].value;
			this.form.wall_title = arr[0].label;
		},
		upload(res, index, lists, name) {
			//图片上传成功
			this.fileList.push(res.data);
		},
		onUploaded() {
			//所有图片上传完成
			this.disabled = false;
		},
		beforeUpload() {
			//上传中 设置不可提交
			this.disabled = true;
			return true;
		},
		onRemove(index, lists, name) {
			this.fileList = lists.map(item => item.response.data);
		},
		submit() {
			if (this.disabled) {
				return this.$refs.uToast.show({
					title: '上传未完成！',
					type: 'error'
				});
			}
			this.$refs.uForm.validate(valid => {
				if (valid) {
					//this.loading = true;
					console.log(this.value.detail.text, this.value.detail.text.length);
					if (this.value.detail.text == '' || this.value.detail.text.length < 10) {
						return this.$refs.uToast.show({
							title: '多说几个字吧！',
							type: 'error'
						});
					}
					article_add({
						...this.form,
						head_img: this.fileList[0],
						content: this.value.detail.html,
						anonymous: this.form.anonymous ? 2 : 1
					})
						.then(res => {
							console.log(res, '发布');
							this.loading = false;
							if (res.code == 200) {
								uni.$emit('add_end'); //刷新文章列表
								this.$refs.uToast.show({
									title: res.data,
									type: 'success'
								});
								this.form = {
									title: '',
									content: '',
									wall: '',
									wall_title: '',
									anonymous: false
								};
								this.fileList = [];
								this.$refs['uUpload'].clear();
								uni.$emit('update_map'); //刷新上个页面
								setTimeout(() => {
									uni.navigateBack({
										delta: 1
									});
								}, 500);
							} else {
								this.$refs.uToast.show({
									title: res.data,
									type: 'error'
								});
							}
						})
						.catch(err => {
							this.loading = false;
							console.log(err);
						});
				} else {
					this.loading = false;
					console.log('验证失败');
				}
			});
		},
		onEditorReady() {
			uni
				.createSelectorQuery()
				.select('#editor')
				.context(function(res) {
					_self.editorCtx = res.context;
				})
				.exec();
		},
		insertImage() {
			// const that = this;
			uni.chooseImage({
				count: 1,
				success: function(res) {
					let filePath = res.tempFilePaths[0];
					uniCloud.uploadFile({
						filePath: filePath,
						cloudPath: new Date().getTime() + '.png',
						onUploadProgress: function(progressEvent) {},
						success(res) {
							_self.editorCtx.insertImage({
								src: res.fileID,
								width: '50%',
								success: function() {
									console.log('插入图片成功');
								}
							});
						},
						fail() {},
						complete() {}
					});
				}
			});
		},
		input(data) {
			//失去焦点时获取输入框内容
			clearTimeout(this.timer); //节流操作
			this.timer = null;
			this.timer = setTimeout(() => {
				console.log(data.detail.html, '输入的内容'); //text
				this.value = data;
			}, 500);
		},
		undo() {
			this.editorCtx.undo();
		},

		redo() {
			this.editorCtx.redo();
		},

		blur() {
			this.editorCtx.blur();
		},

		format(e) {
			let { name, value } = e.target.dataset;
			if (!name) return; // console.log('format', name, value)
			this.editorCtx.format(name, value);
		},

		insertDivider() {
			this.editorCtx.insertDivider({
				success: function() {
					console.log('insert divider success');
				}
			});
		},

		store(e) {
			this.editorCtx.getContents({
				success: function(res) {
					e.currentTarget.id == 1
						? console.log('保存内容:', res.html)
						: uni.navigateTo({
								url: `../preview/preview?rich=${encodeURIComponent(res.html)}`
						  });
				}
			});
		},

		clear() {
			this.editorCtx.clear({
				success: function(res) {
					console.log('clear success');
				}
			});
		},

		removeFormat() {
			this.editorCtx.removeFormat();
		},

		insertDate() {
			const date = new Date();
			const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`;
			this.editorCtx.insertText({
				text: formatDate
			});
		}
	}
};
</script>

<style lang="scss" scoped>
@import '@/static/iconfont.css';

/deep/.ql-editor.ql-blank:before {
	font-style: normal;
	color: #c8c9cb;
}
.editor {
	line-height: 1.2;
	overflow-x: hidden;
	overflow-y: auto;
	word-break: break-all;
}
.icon_img {
	display: flex;
	flex-wrap: wrap;
}
.icon_img .iconfont {
	margin-right: 15rpx;
}
.content {
	padding: 30rpx;
}
</style>
